package com.bootdo.wechat.controller;

import com.bootdo.wechat.constant.BusinessError;
import com.bootdo.wechat.service.MpConfigService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
 * @author songj
 * @version ${VERSION}
 * @Title: bootdo-wechat
 * @Package com.bootdo.wechat.controller
 * @Description: ${TOTO} (用一句话描述该文件做什么)
 * @date 2018/7/31  9:33
 */
@Controller
@RequestMapping("/mp/portal")
public class MpController extends MpBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    MpConfigService mpConfigService;


    @GetMapping(produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String authGet(
            @RequestParam(name = "signature",
                    required = false) String signature,
            @RequestParam(name = "timestamp",
                    required = false) String timestamp,
            @RequestParam(name = "nonce", required = false) String nonce,
            @RequestParam(name = "echostr", required = false) String echostr,@RequestParam(name = "id", required = false) String id) {

        this.logger.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        this.logger.info("canshu=========="+getWxService(id).checkSignature(timestamp, nonce, signature));
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException(BusinessError.PARAM_ILLEGAL.getMessage());
        }
        if (getWxService(id).checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    @ResponseBody
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam(name = "encrypt_type",
                               required = false) String encType,
                       @RequestParam(name = "msg_signature",
                               required = false) String msgSignature,
                       @RequestParam(name = "id", required = false) String id) {
        this.logger.info(
                "\n接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!getWxService(id).checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException(BusinessError.REQUEST_ILLEGAL.getMessage());
        }

        String out = null;
        WxMpXmlMessage inMessage = null;
        if (encType == null) {
            // 明文传输的消息
            inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage,id);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equals(encType)) {
            // aes加密的消息
            inMessage = WxMpXmlMessage.fromEncryptedXml(
                    requestBody, getWxService(id).getWxMpConfigStorage(), timestamp,
                    nonce, msgSignature);
            this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage,id);
            if (outMessage == null) {
                return "";
            }

            out = outMessage
                    .toEncryptedXml(getWxService(id).getWxMpConfigStorage());
        }

        this.logger.debug("\n组装回复信息：{}", out);

        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message,String id) {
        try {
            return getRouter(id).route(message);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }
}
